package hotel.controller.employee;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import java.io.IOException;
import java.util.List;

import hotel.common.MsgBox;
import hotel.dao.HotelDao;
import hotel.modal.Employee;
import javafx.beans.binding.Bindings;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

public class EmployeeManageController {
	@FXML private TableView<Employee> tableView;
	@FXML private TableColumn<Employee, Integer> employeeIdCol;
	@FXML private TableColumn<Employee, String> nameCol;
	@FXML private TableColumn<Employee, String> genderCol;
	@FXML private TableColumn<Employee, String> birthdayCol;
	@FXML private TableColumn<Employee, String> phoneCol;
	@FXML private TableColumn<Employee, String> certIdCol;
	@FXML private TableColumn<Employee, String> entryTimeCol;
	@FXML private TableColumn<Employee, Boolean> statusCol;
	@FXML private TableColumn<Employee, String> addressCol;
	@FXML private Button btnAdd;
	@FXML private GridPane gridPane;
	@FXML private TextField condField;
	@FXML private ChoiceBox<String> condCh;
	@FXML private Button btnQuery;
	@FXML private Button btnRefresh;
	
	@FXML
    public void initialize() {
		employeeIdCol.setCellFactory(new Callback<TableColumn<Employee, Integer>, TableCell<Employee, Integer>>() {
			@Override
			public TableCell<Employee, Integer> call(TableColumn<Employee, Integer> col) {
				return new TableCell<Employee, Integer>() {
					@Override
					protected void updateItem(Integer item, boolean empty) {
						super.updateItem(item, empty);
						if(empty) {
							setText(null);
						}else {
							if(item.intValue() == 0 || item.intValue() == -1) setText("未确定");
							else setText(Integer.toString(item));
						}
						setAlignment(Pos.CENTER);
					}
				};
			}	
		});
		
		nameCol.setCellFactory(col -> new TableCell<Employee, String>() {
			@Override
			protected void updateItem(String item, boolean empty) {
				super.updateItem(item, empty);
				if (empty == true)
					setText(null);
				else setText(item);
				setAlignment(Pos.CENTER);
			}
		});
		
		birthdayCol.setCellFactory(col -> new TableCell<Employee, String>() {
			@Override
			protected void updateItem(String item, boolean empty) {
				super.updateItem(item, empty);
				if (empty == true)
					setText(null);
				else setText(item);
				setAlignment(Pos.CENTER);
			}
		});
		
		nameCol.setCellFactory(col -> new TableCell<Employee, String>() {
			@Override
			protected void updateItem(String item, boolean empty) {
				super.updateItem(item, empty);
				if (empty == true)
					setText(null);
				else setText(item);
				setAlignment(Pos.CENTER);
			}
		});
		
		entryTimeCol.setCellFactory(col -> new TableCell<Employee, String>() {
			@Override
			protected void updateItem(String item, boolean empty) {
				super.updateItem(item, empty);
				if (empty == true)
					setText(null);
				else setText(item);
				setAlignment(Pos.CENTER);
			}
		});
		
		genderCol.setCellFactory(col -> new TableCell<Employee, String>() {
			@Override
			protected void updateItem(String item, boolean empty) {
				super.updateItem(item, empty);
				if (empty == true)
					setText(null);
				else if(item.equals("M")) setText("男");
				else setText("女");
				setAlignment(Pos.CENTER);
			}
		});
		
		// 设置模型Boolean属性和表格String属性之间的转换
		statusCol.setCellFactory(col -> new TableCell<Employee, Boolean>() {
			@Override
			protected void updateItem(Boolean item, boolean empty) {
				super.updateItem(item, empty);
				if (empty == true)
					setText(null);
				else if (item == true)
					setText("在职");
				else
					setText("离职");
				setAlignment(Pos.CENTER);
			}
		});
		
		// 设置表格行右键菜单
		tableView.setRowFactory(new Callback<TableView<Employee>, TableRow<Employee>>() {
			@Override
			public TableRow<Employee> call(TableView<Employee> tableView) {
				final TableRow<Employee> row = new TableRow<>();

				final ContextMenu rowMenu = new ContextMenu();
				MenuItem changeItem = new MenuItem("更改");

				changeItem.setOnAction(new EventHandler<ActionEvent>() {
					@Override
					public void handle(ActionEvent event) {
						Employee employee = row.getItem();
						employeeChange(employee); // 显示员工更改页面
					}
				});

				MenuItem removeItem = new MenuItem("删除");

				removeItem.setOnAction(new EventHandler<ActionEvent>() {
					@Override
					public void handle(ActionEvent event) {
						Boolean ret = MsgBox.showConfirmationDialog("删除确认", null, "你即将删除一个员工个人信息，是否继续？");
						if(!ret) return;
						Employee employee = row.getItem();
						if (HotelDao.delete(employee)) {
							tableView.getItems().remove(employee);
							tableView.refresh();
						} else {
							MsgBox.showErrorDialog("错误", null, "删除失败！");
						}
					}
				});

				rowMenu.getItems().addAll(changeItem, removeItem);
				
				row.setOnMouseClicked(event -> {
			        if (event.getClickCount() == 2 && (! row.isEmpty()) ) {
			            Employee employee = row.getItem();
			            employeeChange(employee);
			        }
			    });

				// only display context menu for non-null items:
				row.contextMenuProperty().bind(Bindings.when(Bindings.isNotNull(row.itemProperty())).then(rowMenu)
						.otherwise((ContextMenu) null));
				return row;
			}
		});
		
		// 监听搜索框enter键按下
		condField.setOnKeyPressed(new EventHandler<KeyEvent>()
	    {
	        @Override
	        public void handle(KeyEvent ke)
	        {
	            if (ke.getCode().equals(KeyCode.ENTER))
	            {
	            	condSearch();
	            	//condField.selectAll();
	            }
	        }
	    });
		
		// 加载数据
		loadData();
		
		// 刷新表格
		tableView.refresh();
		/*
		// 添加条件下拉框监听
		addCondChListener();
		
		// 其他组件初始化
		initOther();
		*/
	}
	
	public void loadData() {
		ObservableList<Employee> data = tableView.getItems();
		data.clear();
		List<Employee> employeeList = HotelDao.getAllEmployee();
		if(employeeList != null) {
			data.addAll(employeeList);
		}
	}
	/*
	public void initOther() {
		
	} 
	
	public void addCondChListener() { 
		condCh.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
			@Override
			public void changed(ObservableValue<? extends String> observable, String oldVal, String newVal) {
				if(newVal.equals("性别")) {
					gridPane.getChildren().remove(node);
				}
				System.out.println("newVal="+newVal);
			}
			
		});
	}
	
	private Node getNodeFromGridPane(GridPane gridPane, int col, int row) {
	    for (Node node : gridPane.getChildren()) {
	        if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) {
	            return node;
	        }
	    }
	    return null;
	}*/
	
	private void employeeChange(Employee employee) {
		FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/hotel/view/employee/EmployeeChange.fxml"));
		try {
			VBox vbox = (VBox) fxmlLoader.load();
			EmployeeChangeController controller = fxmlLoader.<EmployeeChangeController>getController();
			controller.initData(employee); // 向子窗口传递数据
			Stage stage = new Stage();
			stage.setScene(new Scene(vbox));
			stage.setTitle("更改员工信息");
			stage.setResizable(false);
			stage.initModality(Modality.APPLICATION_MODAL);
			stage.showAndWait(); // 显示窗口并等待用户操作
			// ObservableList<Employee> data =
			// tableView.getItems();
			if (employee.isModified()) { // 判断是否被修改
				if (!HotelDao.update(employee)) {
					MsgBox.showErrorDialog("错误", "员工信息修改失败！", "可能输入不规范！");
				}
			}
			tableView.refresh(); // 刷新表格
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// Event Listener on Button[#btnAdd].onAction
	@FXML
	public void onBtnAddAction(ActionEvent event) {
		FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/hotel/view/employee/EmployeeAdd.fxml"));
		try {
			Employee employee = new Employee();
			VBox vbox = (VBox)fxmlLoader.load();
			EmployeeAddController controller = fxmlLoader.<EmployeeAddController>getController();
			controller.initData(employee); // 向子窗口传递数据
			Stage stage = new Stage();
			stage.setScene(new Scene(vbox));
			stage.setTitle("添加员工信息");
			stage.setResizable(false);
			stage.initModality(Modality.APPLICATION_MODAL);
			stage.showAndWait(); // 显示窗口并等待用户操作
			ObservableList<Employee> data = tableView.getItems();
			if(employee.isModified()) { // 判断是否被修改，然后移除以前的员工，并添加新的
				if(HotelDao.add(employee)) { // 如果保存到数据库成功
					int index = data.size();
					data.add(index, employee);
					tableView.getSelectionModel().select(index);
				}else {
					MsgBox.showErrorDialog("错误", "员工信息修改失败！", "可能输入不规范！");
				}
				
			}
			tableView.refresh(); // 刷新表格
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// Event Listener on Button[#btnQuery].onAction
	@FXML
	public void onBtnQueryAction(ActionEvent event) {
		this.condSearch();
	}
	
	private void condSearch() {
		String col = condCh.getSelectionModel().getSelectedItem();
		String cond = condField.getText();
		ObservableList<Employee> data = tableView.getItems();
		List<Employee> employeeList = HotelDao.getEmployeeCondSearch(col, cond);
		if(employeeList != null) {
			data.clear();
			data.addAll(employeeList);
		}else {
			data.clear();
		}
		tableView.refresh();
	}
	
	// Event Listener on Button[#btnRefresh].onAction
		@FXML
		public void onBtnRefreshAction(ActionEvent event) {
			loadData();
			condField.clear();
			condCh.getSelectionModel().select("全部");
		}
}
